<?php

class DependenteController extends AdminController implements ItemMenu {
	
	/* (non-PHPdoc)
	 * @see ItemMenu::cadastrar()
	 */
	public function cadastrar() {
		
		if( isset($_POST) && count($_POST) > 0 ){ 
			
			$this->salvar();
		
		}else{
		
			$view = new View("dependente/gerenciar");
		
			$condominio_id = 
				$this->isAdministrador() ? $this->getParam("condominio_id") : Encryption::encode( $this->auth->getUserData("condominio_id") );
			$view->set("condominio.id", $condominio_id);
			
			$clienteParent_id = 
				$this->isAdministrador() ? $this->getParam("cliente_id") : Encryption::encode( $this->auth->getUserData("cliente_id") );
			$view->set("cliente.cliente.id", $clienteParent_id);
			
			//$usuarioModel = new UsuarioModel();
			//$usuario = $usuarioModel->findOne( array( "cliente_id" => $clienteParent_id ) );
			//$permissaoName = $usuario["tipo_permissao_id"];
			$tipoPermissaoModel = new TipoPermissaoModel();
			$tipoPermissao = $tipoPermissaoModel->findOne( array( "nome" => "Condômino" ) );
			$permissaoName = $tipoPermissao["id"];
			
			// Identificação
			$view->set("cliente.id", "");
			$view->set("cliente.ativo1", "checked");
			$view->set("cliente.nome", "");
			$view->set("cliente.telefone", "");
			$view->set("cliente.data.nascimento", "");
			$view->set("cliente.cpf", "");
			
			// Conta de usuário
			$view->set("usuario.id", "");
			$view->set("usuario.email", "");
			$view->set("usuario.nome", "");
			$view->set("usuario.tipo.permissao", 
				$this->isAdministrador() ? 
					HtmlComponent::select( "Perfil", "small", "usuario_tipo_permissao_id", TipoPermissaoModel::convertToSelectArray() ) : 
					HtmlComponent::inputHidden( "Perfil", "small", "usuario_tipo_permissao_id", $permissaoName)
			);
		
			// Form
			$view->set("form.controller", $this->getController() );
			$view->set("form.action", $this->getAction() );
			$view->set("form.title.action", ucfirst( $this->getAction() ));
								
			$this->template->content = $view;
			
		}
		
	}

	/* (non-PHPdoc)
	 * @see ItemMenu::editar()
	 */
	public function editar() {
		
		if( isset($_POST) && count($_POST) > 0 ){ 
			
			$this->salvar();
		
		}else{
			
			$idParam = $this->getIdFrom("id");
			$cliente = null;
			
			$clienteModel = new ClienteModel();
			
			if( $this->testIsValidId( $idParam ) )
				$cliente = $clienteModel->findById( $idParam );
			
			if( $cliente != null && is_array($cliente) && count($cliente) > 0 ){
				
				$usuarioModel = new UsuarioModel();
				$usuario = $usuarioModel->findOne( array( "cliente_id" => $cliente["id"] ) );
				
				$view = new View("dependente/gerenciar");
				$view->set("condominio.id", Encryption::encode($cliente["condominio_id"]));
	
				// Identificação
				$view->set("cliente.id", Encryption::encode($cliente["id"]));
				$view->set("cliente.ativo".$cliente["ativo"], "checked");
				$view->set("cliente.nome", $cliente["nome"]);
				$view->set("cliente.telefone", Mask::maskNumber($cliente["telefone"], Mask::$TELEFONE));
				$view->set("cliente.data.nascimento", DateUtil::convertDate($cliente["data_nascimento"], DateUtil::$EN_US, DateUtil::$PT_BR));
				$view->set("cliente.cpf", Mask::maskNumber($cliente["cpf"], Mask::$CPF));
				$view->set("cliente.cliente.id", Encryption::encode($cliente["cliente_id"]));
				
				// Conta de usuário
				$view->set("usuario.id", Encryption::encode($usuario["id"]));
				$view->set("usuario.email", $usuario["email"]);
				$view->set("usuario.nome", $usuario["nome"]);
				$view->set("usuario.tipo.permissao", 
					$this->isAdministrador() ? 
						HtmlComponent::select( "Perfil", "small", "usuario_tipo_permissao_id", TipoPermissaoModel::convertToSelectArray($usuario["tipo_permissao_id"]) ) : 
						HtmlComponent::inputHidden( "Perfil", "small", "usuario_tipo_permissao_id", $usuario["tipo_permissao_id"])
				);
			
				// Form
				$view->set("form.controller", $this->getController() );
				$view->set("form.action", $this->getAction() );
				$view->set("form.title.action", ucfirst( $this->getAction() ));
									
				$this->template->content = $view;
				
			}else{
				
				$this->redirecionaAcessoIdInvalido("Dependente", "dependente");
				
			}
			
		}
	
	}

	/* (non-PHPdoc)
	 * @see ItemMenu::apagar()
	 */
	public function apagar() {
		
		$idParam = $this->getIdFrom();
	
		if( $this->testIsValidId($idParam) ){
		
			$clienteModel = new ClienteModel();
			$dependente = $clienteModel->delete($idParam);
			
			$this->addGrowlMsgs( Messages::get("apagadoComSucesso", array( "{objeto}" => $dependente['nome'] )) );
			$urlToRedirect  = "dependente/index";
			$urlToRedirect .= "/condominio_id/".Encryption::encode( $dependente['condominio_id'] );
			$urlToRedirect .= "/cliente_id/".Encryption::encode( $dependente['cliente_id'] );
			$this->redirect->goToUrl( $urlToRedirect );
			
		}else{
			
			$this->redirecionaAcessoIdInvalido("Dependente", "dependente");
						
		}
		
	}

	/* (non-PHPdoc)
	 * @see ItemMenu::listar()
	 */
	public function listar() {
		
		$params = array();
		
		if( $this->isAdministrador() ){
			
			if( $this->containsParam("condominio_id") )
				$params["condominio_id"] = $this->getIdFrom("condominio_id");
			if( $this->containsParam("cliente_id") )
				$params["cliente_id"] = $this->getIdFrom("cliente_id");
				
		}else{
			
			$params["condominio_id"] = $this->auth->getUserData("condominio_id");
			$params["cliente_id"] = $this->auth->getUserData("cliente_id");
		
		}
		
		$view = new View("dependente/listar");
		
		if( count($params) == 0 ){
			
			$view->set( "select.condominio", 
				HtmlComponent::select( "Condomínio", "medium", "condominio_id", CondominioModel::convertAllToSelectArray(), "condominio")
			);
			$view->set( "select.cliente", "");
			$view->set( "table.results", "");
			$view->set( "panel", "Filtrar");
			
		}else{
			 
			if( array_key_exists("condominio_id", $params) ){
				
				if( array_key_exists("cliente_id", $params) ){
					
					$clienteModel = new ClienteModel();
					$cliente = $clienteModel->findById( $params["cliente_id"] );
					
					$table = new View("_components/jquery_table");
		
					$table->set("table.title", "Dependentes de ".$cliente["nome"]);
					$table->set("table.black.icon16", "list");
					$table->set("table.new.label", "Novo Dependente");
					$table->set("table.new.url", 
							"dependente/cadastrar" . 
							"/condominio_id/" . Encryption::encode( $params["condominio_id"] ) . 
							"/cliente_id/" . Encryption::encode( $params["cliente_id"] )
					);
					
					$table->set("table.head", 
						ViewList::merge( "th",
							ClienteModel::createHeadersToTable()
						) 
					);
					
					$table->set("table.body", 
						ViewList::merge( "cliente/tr", 
							ClienteModel::listDependentesToTableByCondominioAndCliente($params["condominio_id"], $params["cliente_id"])
						) 
					);
					
					$view->set( "select.condominio", "");
					$view->set( "select.cliente", "");
					$view->set( "table.results", $table->output()); // Criar tabela
					$view->set( "panel", "Listagem");
				
				}else{

					$condominioModel = new CondominioModel();
					$condominio = $condominioModel->findById( $params["condominio_id"] );
					
					$inputHidden = HtmlComponent::inputHidden("Condomínio", "medium", "condominio_id", Encryption::encode($condominio["id"]) );
					
					if( $this->isAdministrador() )
						$view->set( "select.condominio", 
								$inputHidden . HtmlComponent::inputText("Condomínio", "medium", "", $condominio["nome"], true) );
					else
						$view->set( "select.condominio", $inputHidden );
					
					$view->set( "select.cliente", HtmlComponent::select( "Cliente", "medium", "cliente_id", 
							ClienteModel::convertClientePorCondominioToSelectArray( $condominio["id"] ), "cliente") );
					$view->set( "table.results", "");
					$view->set( "panel", "Filtrar");
				
				}
				
			}else{
				
				$this->redirecionaAcessoIdInvalido("Condomínio", "dependente", true);
			
			}
			
		}
		
		$view->set("controller", $this->getController() );
		$view->set("controllerLabel", ucfirst($this->getController()) );
		$view->set("action", "listar" );
		
		$this->template->content = $view;
		
	}

	/* (non-PHPdoc)
	 * @see ItemMenu::ver()
	 */
	public function ver() {
		$idParam = $this->getIdFrom();
		if( $this->testIsValidId($idParam) ){ 
			echo "aki";
		}else{
			$this->redirect->goToAction("listar");
		}
	}

	private function salvar() {
		
		//print_r($_POST);
		//exit();
		
		$condominio = array();
		$cliente = array();
		$usuario = array();
		
		foreach ( $_POST as $key => $value ){
			$camp = explode("_", $key);
			$type = array_shift( $camp );
			$camp = implode("_", $camp);
			if( $camp != "senha2" ){
				if( $camp == "id" || ( substr( $camp, (strlen($camp)-3) ) == "_id" ) ){
					if( $value != "" )
						${$type}[$camp] = Encryption::decode($value);
				}else{
					if( in_array($camp, array( "cep", "telefone", "cpf", "cnpj" )) )
						${$type}[$camp] = Mask::unMaskNumber($value);
					else if( in_array($camp, array( "data_nascimento" )) )
						${$type}[$camp] = DateUtil::convertDate($value, DateUtil::$PT_BR, DateUtil::$EN_US);
					else if( $camp == "senha" )
						${$type}[$camp] = md5($value);
					else
						${$type}[$camp] = $value;
				}
			}
		}
		
		if( count($condominio) == 1 && array_key_exists("id", $condominio) ){
		
			$clienteModel = new ClienteModel();
			$usuarioModel = new UsuarioModel();
			
			$clienteParent = $clienteModel->findById( $cliente['cliente_id'] );
			
			// Ok - Cliente
			$cliente['condominio_id'] = $condominio['id'];
			$cliente['endereco_id'] = $clienteParent['endereco_id'];
			$cliente['unidade_id'] = $clienteParent['unidade_id'];
			$cliente['cliente_id'] = $clienteParent['id']; // ( ( $clienteParent['id'] == 0 ) ? "Titular" : "Dependente" ) 
			$cliente = $clienteModel->save($cliente);
			
			// Verifica se é registro novo
			$isNovoModel = !isset($usuario['id']);
	
			// Ok - Usuario
			$usuario['condominio_id'] = $condominio['id'];
			$usuario['cliente_id'] = $cliente['id'];
			$usuario = $usuarioModel->save($usuario);
			
			// Define a mensagem do aviso
			$msgKey = $isNovoModel ? "salvoComSucesso" : "alteradoComSucesso";
			$this->addGrowlMsgs( Messages::get( $msgKey, array( "{objeto}" => "'".$cliente['nome']."' (Dependente)")) );
			// Redireciona para index do controller 
			$urlToRedirect  = "dependente/index";
			$urlToRedirect .= "/condominio_id/".Encryption::encode( $cliente['condominio_id'] );
			$urlToRedirect .= "/cliente_id/".Encryption::encode( $cliente['cliente_id'] );
			$this->redirect->goToUrl( $urlToRedirect );
			exit();
			
		}else{
			
			$this->addGrowlMsgs( Messages::get("dadosInvalidos", array( "{objeto}" => "Dependente" )) );
			$urlToRedirect  = "dependente/index";
			$urlToRedirect .= "/condominio_id/".Encryption::encode( $cliente['condominio_id'] );
			$urlToRedirect .= "/cliente_id/".Encryption::encode( $cliente['cliente_id'] );
			$this->redirect->goToUrl( $urlToRedirect );
			
		}
		
	}

}

?>